package com.fqy.ticket.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.fqy.ticket.business.domain.Train;
import com.fqy.ticket.business.domain.TrainExample;
import com.fqy.ticket.business.mapper.TrainMapper;
import com.fqy.ticket.business.req.TrainQueryReq;
import com.fqy.ticket.business.req.TrainSaveReq;
import com.fqy.ticket.business.resp.TrainQueryResp;
import com.fqy.ticket.common.exception.BusinessException;
import com.fqy.ticket.common.exception.BusinessExceptionEnum;
import com.fqy.ticket.common.resp.PageResp;
import com.fqy.ticket.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TrainService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainService.class);

    @Resource
    private TrainMapper trainMapper;

    /**
     * 保存Train记录（新增或更新）
     * @param req 保存请求对象
     */
    public void save(TrainSaveReq req) {
        DateTime now = DateTime.now();
        Train train = BeanUtil.copyProperties(req, Train.class);

        if (ObjectUtil.isNull(train.getId())) {
            // 保存之前，先校验唯一键是否存在
            Train trainDB = selectByUnique(req.getCode());
            if (ObjectUtil.isNotNull(trainDB)) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CODE_UNIQUE_ERROR);
            }
            // 新增逻辑
            train.setId(SnowUtil.getSnowflakeNextId());
            train.setCreateTime(now);
            train.setUpdateTime(now);
            trainMapper.insert(train);
            LOG.info("新增Train成功，ID：{}", train.getId());
        } else {
            // 更新逻辑
            train.setUpdateTime(now);
            trainMapper.updateByPrimaryKey(train);
        }
    }

    /**
     * 分页查询Train列表
     * @param req 查询请求对象（包含分页信息）
     * @return 分页结果
     */
    public PageResp<TrainQueryResp> queryList(TrainQueryReq req) {
        TrainExample trainExample = new TrainExample();
        trainExample.setOrderByClause("code asc");
        TrainExample.Criteria criteria = trainExample.createCriteria();

        LOG.info("查询Train列表，页码：{}，每页条数：{}", req.getPage(), req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Train> trainList = trainMapper.selectByExample(trainExample);

        PageInfo<Train> pageInfo = new PageInfo<>(trainList);
        LOG.info("查询结果：总行数={}，总页数={}", pageInfo.getTotal(), pageInfo.getPages());

        List<TrainQueryResp> list = BeanUtil.copyToList(trainList, TrainQueryResp.class);

        PageResp<TrainQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 根据ID删除Train记录
     * @param id 记录ID
     */
    public void delete(Long id) {
        int count = trainMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public List<TrainQueryResp> queryAll() {
        List<Train> trainList = selectAll();
        // LOG.info("再查一次");
        // trainList = selectAll();
        // LOG.info("再查一次");
        // trainList = selectAll();
        return BeanUtil.copyToList(trainList, TrainQueryResp.class);
    }

    public List<Train> selectAll() {
        TrainExample trainExample = new TrainExample();
        trainExample.setOrderByClause("code asc");
        return trainMapper.selectByExample(trainExample);
    }

    public Train selectByUnique(String code) {
        TrainExample example = new TrainExample();
        TrainExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        List<Train> list = trainMapper.selectByExample(example);
        return CollUtil.isEmpty(list) ? null : list.get(0);
    }
}